from django.shortcuts import render

# Create your views here.
# GET /areas/infos/
from rest_framework import status

from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreasInfoSerializer,AreasCitySerializer, ProvinceSerializer,  \
    SubsCitysSerializer
from rest_framework_extensions.cache.decorators import cache_response


# 显示省级视图函数
class AreasInfoAPIView(APIView):
    # @cache_response()
    def get(self,request):
        # select *from tb_areas where parent_id is null;
        # 获取数据(查询数据库),检查数据,返回相应
        provinces=Area.objects.filter(parent=None)

        serializer=AreasInfoSerializer(provinces,many=True)

        return Response(serializer.data)
# 显示城市视图函数 GET/areas/infos/(?P<pk>\d+)/
class AreasCityAPIView(APIView):
    # 不需要登录也可以展示地区
    # @cache_response()
    def get(self,request,pk):
        # citys=Area.objects.filter(parent_id=pk)
        citys=Area.objects.filter(parent=pk)
        serializer=AreasCitySerializer(citys,many=True)
        try:
            province=Area.objects.get(id=pk)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        data={
            "id":pk,
            "name":province.name,
            "subs":serializer.data
        }
        return Response(data)
# ??????装饰器实现redis缓存省市区数据
        # (没实现,查询出来的市级信息与区县信息相同,因为缓存的redis数据一样,而且在数据没过期前,市级信息与县级信息不变)

# 收获地址



# viewset视图集实现省市区数据显示
class AreasInfoViewset(CacheResponseMixin,ReadOnlyModelViewSet):
    # 不使用全局分页器
    pagination_class = None
    def get_queryset(self):
        if self.action=='list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()
    def get_serializer_class(self):
        if self.action=='list':
            return ProvinceSerializer
        else:
            return SubsCitysSerializer